<?
if (eregi(basename( __FILE__ ), $_SERVER['PHP_SELF'])) {
	print "<h1>Incorrect access</h1>You cannot access this file directly.";
	exit();
}
//TuanNK 20090113


//maybe we create new function for handling this
function init_session_cookies($path="/", $domain="") {
  if ($domain=='localhost') $domain='';
  if (function_exists('session_set_cookie_params')) {
    session_set_cookie_params(0, $path, $domain);
  } else {
    ini_set('session.cookie_lifetime', '0');
    ini_set('session.cookie_path', $path);
    ini_set('session.cookie_domain', $domain);
  }
}

if(WEB_DOMAIN)
{
	$cookie_path = '/';
	
	if(eregi(WEB_DOMAIN, $_SERVER['HTTP_HOST']))
	{
		$cookie_domain = '.'.WEB_DOMAIN; //or any valid domain
	}
	else{
		$cookie_domain = "localhost";
	}
	
	init_session_cookies($cookie_path, $cookie_domain);
}
else{
	init_session_cookies('/', $_SERVER['HTTP_HOST']);
}

if (defined('DEBUG') && DEBUG && class_exists('CGlobal') && isset($start_rb)){
	global $start_rb;
	$mtime = microtime();
	$mtime = explode(" ",$mtime);
	$mtime = $mtime[1] + $mtime[0];
	$end_rb = $mtime;			
	$load_time = round(($end_rb - $start_rb),5)."s";					 		
	CGlobal::$conn_debug.= " <b>Connect to Memcache session server : ".MEMCACHE_SESSION_HOST." : ".MEMCACHE_SESSION_PORT." </b> [in $load_time]<br>\n";
}			
		
ini_set('session.gc_maxlifetime', _SESS_TIME_EXPIRE);

// below sample main
session_start();
//session_regenerate_id(true);

if(basename($_SERVER['PHP_SELF'])=='index.php')
{
	function update_user_online()
	{
		$user_id   = isset($_SESSION['user_id'])?(int)$_SESSION['user_id']:0;
		
		//if($user_id)
		{
			$session_id = session_id();
			$page     ='';
			$page_id  =0;
			$user_name = isset($_SESSION['user_name'])?$_SESSION['user_name']:0;
		
			$login_type = (isset($_SESSION['openid_url']) && $_SESSION['openid_url']!='')?1:0;
			$open_id    = (isset($_SESSION['openid_url']) && $_SESSION['openid_url']!='')?$_SESSION['openid_url']:'';
	    	
			if(class_exists('AZNet')){
				$page		=AZNet::$page['name'];
				$page_id	=(int)AZNet::$page['id'];
			}
			
			if(($page=='ItemDetail' || $page=='item_detail') && isset($_GET['id']) && $_GET['id']){
				$item_id=(int)$_GET['id'];
			}
			else{
				$item_id=0;
			}
			
			if(in_array(basename($_SERVER['PHP_SELF']),array('ebxml.php','ajax.php','captcha.php'))){
				$ref_url='';
			}
			else{
				AZLib::check_uri();	
				$ref_url=CGlobal::$query_string;
			}
			
			$sql = "SELECT  session_referer, page, page_id, item_id FROM "._SESS_TABLE." WHERE session_id = '$session_id'";
		    $result = DB::query($sql,__LINE__.__FILE__);
		   
		    if (mysql_num_rows($result)) {
		        $s_row = mysql_fetch_assoc($result);
		    }
		    else{
		    	 $s_row = array();
		    }
			
			if($s_row){
				if($ref_url=='' || in_array(basename($_SERVER['PHP_SELF']),array('ebxml.php','ajax.php','captcha.php'))){
		    		$ref_url=stripslashes($s_row['session_referer']);
		    	}
				
				if(!$page) 					$page 		= $s_row['page'] ;
				if(!$page_id) 				$page_id 	= (int)$s_row['page_id'] ;
				if(!$item_id) 				$item_id 	= (int)$s_row['item_id'] ;
				
				$sql = "UPDATE "._SESS_TABLE." SET
												  	session_expires = ".time().", 
												  	session_referer = '".addslashes($ref_url)."',
												  	session_ip 		= '".$_SERVER['SERVER_ADDR'].'::'.$_SERVER['REMOTE_ADDR']."', 
												  	page 			= '$page',	
												  	page_id 		= $page_id,
												  	category_id 	= ".CGlobal::$curCategory.",
												  	item_id 		= $item_id,
												  	user_id 		= '$user_id',
												  	user_name		= '$user_name',
												  	login_type		= '$login_type',
												  	open_id			= '$open_id'
												WHERE session_id 	= '$session_id'";
			}
			else{
				$sql = "INSERT INTO "._SESS_TABLE." 
								  (
								  	session_id, 
								  	session_expires,  
								  	session_referer, 
								  	session_ip,   
								  	page,  
								  	page_id, 
								  	category_id, 
								  	item_id, 
								  	user_id,  
								  	user_name,
								  	login_type,
								  	open_id
								  	) 
		                   VALUES (
		                   			'$session_id', 				
		                   			".time().", 			
		                   			'".addslashes($ref_url)."', 	   
		                   			'".$_SERVER['SERVER_ADDR'].'::'.$_SERVER['REMOTE_ADDR']."',	
		                   			'$page',	  
		                   			$page_id,		   
		                   			".CGlobal::$curCategory.", 		 
		                   			$item_id, 	  
		                   			$user_id ,		
		                   			'$user_name' ,		
		                   			$login_type ,		
		                   			'$open_id')";
			}
		                   
			DB::query($sql,__LINE__.__FILE__);
			
			if(User::is_login() && MEMCACHE_ON)//Nếu đã đăng nhập
			{
				$user = User::$current->data;
				if($user && !isset($user['last_login']) || (isset($user['last_login']) && $user['last_login']<(TIME_NOW-300))){
					DB::query("UPDATE user SET last_login=".TIME_NOW." WHERE id={$user['id']}");
					
					$user_memcache = AZMemcache::do_get("user:{$user['id']}");
					if($user_memcache){
						$user_memcache['last_login'] = TIME_NOW;
						AZMemcache::do_put("user:{$user['id']}", $user_memcache);
					}
				}
			}
			
			
		}
		
		if(StaticCache::notExistCache('del_exs',1)){//Run 1 cronjob/15s
			StaticCache::startCache();
			StaticCache::endCache();
			
			DB::query("DELETE FROM "._SESS_TABLE." WHERE session_expires <= " . (time() - _SESS_TIME_EXPIRE));
		}
	}
	
	register_shutdown_function("update_user_online");
}
?>